package com.mspbots.api.service.impl;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.mspbots.api.service.TenantUserMappingService;
import com.mspbots.cw.request.TenantUserDTO;
import com.mspbots.cw.request.TenantUsersMappingDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;

/**
 * com.mspbots.api.service.TenantUserImpl
 *
 * @author Alex bob(https://github.com/vnobo)
 * @date Created by 2019/6/19
 */
@Deprecated
@Slf4j
@Service
public class TenantUserMappingServiceImpl extends BaseGenericService implements TenantUserMappingService {

    public List<TenantUserDTO> addBatch(List<TenantUserDTO> tenantUsers) {
        Mono<JsonNode> resultMono = this.apiClient.post("/tenant/user/add-batch", tenantUsers);
        JsonNode result = resultMono.block();
        tenantUsers = this.objectMapper.convertValue(result, new TypeReference<List<TenantUserDTO>>() {
        });
        return tenantUsers;
    }

    @Override
    public TenantUsersMappingDTO findByTenantUser(Long tenantId, Long tenantUserId) {

        try {
            Mono<JsonNode> resultMono = this.apiClient.get("/user-mapping/user",
                    Map.of("tenantId", tenantId, "tenantUserId", tenantUserId));
            JsonNode result = resultMono.blockOptional().orElse(null);
            if (ObjectUtils.isEmpty(result)) {
                return null;
            }

            return this.objectMapper.convertValue(result, TenantUsersMappingDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("get user mapping error! {}", tenantUserId);
        }
        return null;

    }

    @Override
    public TenantUsersMappingDTO findBySheetUser(Map<String, Object> params) {

        try {
            Mono<JsonNode> resultMono = this.apiClient.get("/user-mapping/user", params);
            JsonNode result = resultMono.blockOptional().orElse(null);

            if (ObjectUtils.isEmpty(result)) {
                return null;
            }
            return this.objectMapper.convertValue(result, TenantUsersMappingDTO.class);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("get tsheet_user_id mapping error! {}", params.get("sheetUserId"));
        }
        return null;

    }

}
